package com.lbh.graphics;

import com.jogamp.opengl.cg.CGcontext;
import com.jogamp.opengl.cg.CGparameter;
import com.jogamp.opengl.cg.CGprogram;
import com.jogamp.opengl.cg.CgGL;

import java.io.IOException;

/***
 * project:JRuntime
 * package:com.lbh.graphics
 *
 * @author user:lenovo QQ:1601078366
 * @date 2021/10/21 23:20
 * @version V1.0
 */
public class CGProgram {

    private static CGcontext context = null;
    private static CGprogram program = null;
    private static CGparameter KdParam = null;
    private static CGparameter MVPParam = null;
    private static CGparameter TestColorParam = null;
    private static /*CGprofile*/ int profile;

    static {
        String os = System.getProperty("os.name").toLowerCase();
        profile = os.startsWith("mac os") ? CgGL.CG_PROFILE_ARBVP1 : CgGL.CG_PROFILE_VP20;
    }

    public void initCG() {
        context = CgGL.cgCreateContext();
        checkCgError();

        /* Test adding source text to context */
        try {
            //noinspection ConstantConditions
            program = CgGL.cgCreateProgramFromStream(
                    context, CgGL.CG_SOURCE,
                    getClass().getClassLoader().getResourceAsStream("example.cg"),
                    profile, null, null);
        } catch (IOException e) {
            throw new RuntimeException("Error loading Cg vertex program", e);
        }
        checkCgError();

        System.err.println("LAST LISTING----" + CgGL.cgGetLastListing(context) + "----\n");

        System.err.println("---- PROGRAM BEGIN ----\n"+
                CgGL.cgGetProgramString(program, CgGL.CG_COMPILED_PROGRAM)+
                "---- PROGRAM END ----\n");

        if(program != null)
        {
            CgGL.cgGLLoadProgram(program);
            checkCgError();

            KdParam = CgGL.cgGetNamedParameter(program, "Kd");
            checkCgError();

            MVPParam = CgGL.cgGetNamedParameter(program, "MVPMatrix");
            checkCgError();

            TestColorParam = CgGL.cgGetNamedParameter(program, "v.TestColor");
            checkCgError();
        }
    }

    private static void checkCgError() {
        /*CGerror*/ int err = CgGL.cgGetError();

        if (err != CgGL.CG_NO_ERROR) {
            System.out.println("CG error: " + CgGL.cgGetErrorString(err));
            System.exit(1);
        }
    }
}
